﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace InkCanvasDemo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            
        }

        private void 打开图片显示在InkCanvas上(object sender, RoutedEventArgs e)
        {
            BitmapImage bitmapSource = new BitmapImage(new Uri($"{AppDomain.CurrentDomain.BaseDirectory}/res/1.png"));
            ink.Background = new ImageBrush(bitmapSource);
        }

        private void 保存(object sender, RoutedEventArgs e)
        {
            //96d可以保存窗口大小的图片
            RenderTargetBitmap render = new RenderTargetBitmap((int)ink.ActualWidth, (int)ink.ActualHeight, 96d, 96d, PixelFormats.Pbgra32);
            render.Render(ink);

            BitmapEncoder encoder = new PngBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(render));
            string file = "1.png";
            using (Stream stm = File.Create(file))
            {
                encoder.Save(stm);
            }
        }

        Stack<Stroke> undo = new Stack<Stroke>(10);
        Stack<Stroke> redo = new Stack<Stroke>(10);

        private void 撤回(object sender, RoutedEventArgs e)
        {
            if (undo.Count > 0)
            {
                // 将最后一次添加的笔迹从 undoStack 中弹出
                Stroke stroke = undo.Pop();
                // 将该笔迹添加到 redoStack 中
                redo.Push(stroke);
                // 从 InkCanvas 中移除该笔迹
                ink.Strokes.Remove(stroke);
            }
        }

        private void 恢复(object sender, RoutedEventArgs e)
        {
            if (redo.Count > 0)
            {
                // 将最后一次添加的笔迹从 undoStack 中弹出
                Stroke stroke = redo.Pop();
                // 将该笔迹添加到 redoStack 中
                undo.Push(stroke);
                // 从 InkCanvas 中移除该笔迹
                ink.Strokes.Add(stroke);
            }
        }
        /// <summary>
        /// 每有一个新的stroke就将redo恢复的清空
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ink_StrokeCollected(object sender, InkCanvasStrokeCollectedEventArgs e)
        {
            undo.Push(e.Stroke);
            redo.Clear();
        }
    }
}
